﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Model;
using System.Security.Cryptography;
using System.Text;
using BusinessLogic.Command;
using System.Configuration;
using System.Net.Mail;
using System.Web.Security;
//using Telerik.Web.UI;

namespace CO9APPFORM
{
    public partial class CandidateInfo : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            NeedAllowRole("Recruit", "Default.aspx");

            if (Page.IsPostBack == false)
            {
                divMain.Visible = true;
                divSuccess.Visible = false;

                BindControl();

                if (Request.QueryString["hash"] != null)
                {
                    ViewState["PID"] = GetValue(Request.QueryString["hash"].ToString());
                }
                else
                {
                    ViewState["PID"] = 0;
                }
            }
        }

        private int GetValue(string p)
        {
            GetPersonalInfoCommand cmd = new GetPersonalInfoCommand(p);
            cmd.Execute();

            if (cmd.Result != null)
            {
                txtName.Text = cmd.Result.FNAME_EN;
                txtSurname.Text = cmd.Result.LNAME_EN;
                txtEmail.Text = cmd.Result.EMAIL;
                ddlPosApplyFor.SelectedValue = cmd.Result.POSITION;
                txtAdditionalNote.Text = cmd.Result.NOTE;

                return cmd.Result.ID;
            }

            return 0;
        }

        protected void BindControl() {
            CubeOfDB2Entities db = new CubeOfDB2Entities();
            ddlPosApplyFor.DataSource = db.APP_POSITION.ToList();
            ddlPosApplyFor.DataTextField = "NAME_EN";
            ddlPosApplyFor.DataValueField = "NAME_EN";
            ddlPosApplyFor.DataBind();
            ddlPosApplyFor.Items.Insert(0, new ListItem("Please Select", ""));
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            string hash;

            using (MD5 md5Hash = MD5.Create())
            {
                hash = GetMd5Hash(md5Hash, Guid.NewGuid().ToString());
            }

            APP_PERSONAL P = new APP_PERSONAL();
            P.ID = Convert.ToInt32(ViewState["PID"]);
            P.HASH = hash;
            P.FNAME_EN = txtName.Text;
            P.LNAME_EN = txtSurname.Text;
            P.EMAIL = txtEmail.Text;
            P.POSITION = ddlPosApplyFor.SelectedValue;
            P.NOTE = txtAdditionalNote.Text;
            P.APP_DATE = DateTime.Today;

            MaintainTXCommand cmd = new MaintainTXCommand(P);
            cmd.Execute();

            /* send email */
            try
            {
                string frommail = ConfigurationManager.AppSettings["Email_From"].ToString();
                string toccmail = ConfigurationManager.AppSettings["Email_To"].ToString();
                string subject = ConfigurationManager.AppSettings["Email_Subject"].ToString();
                string host = ConfigurationManager.AppSettings["Email_SmtpHost"].ToString();
                int port = int.Parse(ConfigurationManager.AppSettings["Email_SmtpPort"].ToString());
                string _user = ConfigurationManager.AppSettings["Email_User"];
                string _password = ConfigurationManager.AppSettings["Email_Password"];
                string linkpage = ConfigurationManager.AppSettings["Email_LinkPage"];
                string body = "";
                string toEmail = "";
                string toCCEmail = "";

                toEmail = txtEmail.Text;
                toCCEmail = toccmail;
                body = ConfigurationManager.AppSettings["Email_Body"]; // "There is an application has been registered by K." + txtName.Text + " " + txtSurname.Text + "<br>";
                body = body.Replace("{NAME}", txtName.Text);
                body = body.Replace("{SURNAME}", txtSurname.Text);
                body = body.Replace("{POSITION}", ddlPosApplyFor.SelectedValue);
                if (txtAdditionalNote.Text.Length > 0)
                    body = body.Replace("{NOTE}", "Note : " + txtAdditionalNote.Text);
                else
                    body = body.Replace("{NOTE}", "");
                body = body.Replace("{LINK}", "<a href='" + linkpage + "?Hash=" + hash + "'>[Fill Application Form]</a>");
                body = body.Replace("{NEXTROW}", "<br>");

                MailMessage mail = new MailMessage();
                mail.From = new MailAddress(frommail);
                mail.Subject = subject;
                mail.To.Add(toEmail);
                mail.CC.Add(toCCEmail);
                mail.Body = body;
                mail.IsBodyHtml = true;
                SmtpClient smtp = new SmtpClient(host, port);
                smtp.Credentials = new System.Net.NetworkCredential(_user, _password);
                smtp.EnableSsl = true;
                smtp.Send(mail);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            /* */

            divMain.Visible = false;
            divSuccess.Visible = true;
        }

        static string GetMd5Hash(MD5 md5Hash, string input)
        {
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            return sBuilder.ToString();    
        }

        protected void btnClosePage_Click(object sender, EventArgs e)
        {
            this.ClientScript.RegisterClientScriptBlock(this.GetType(), "Close", "window.close()", true);
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("CandidateInfoList.aspx");
        }
    }
}